<template>
  <div>
    <el-dialog
    title="提示"
    :visible.sync="dialogVisible"
    width="50%"
    :before-close="handleClose">
      <div>
       <el-form :model="ruleForm2"  :rules="rules2" ref="ruleForm2" label-width="100px" class="demo-ruleForm">
          <el-form-item label="账号" prop="name">
            <el-input :disabled="unamesta" v-model="ruleForm2.name" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input type="password" v-model="ruleForm2.pass" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input type="password" v-model="ruleForm2.checkPass" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="userNick">
            <el-input v-model.number="ruleForm2.userNick"></el-input>
          </el-form-item>
          <el-form-item label="权限角色" prop="role">
            <el-select v-model="ruleForm2.role" placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm2')">取 消</el-button>
        <el-button type="primary" v-if="!userData.id" @click="submitForm('ruleForm2')">确 定</el-button>
        <el-button type="primary" v-else @click="editUser()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import crypto from 'crypto'
import Http from '@/Http/Http'

export default {
  
  data() {
    var userNick = (rule, value, callback) => {
      if (value === '') {
       callback(new Error('请输入昵称'));
      } else {
        callback();
      }
    };
    var name = (rule, value, callback) => {
      
      if (value === '') {
        callback(new Error('用户名'));
      } else {
        callback();
      }
    };
    var pass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm2.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
    var role = (rule, value, callback) => {
      if (value === '') {
       callback(new Error('请选择角色'));
      } else {
        callback();
      }
    };
    return {
      unamesta:false,
      ruleForm2: {
        name: '',
        userNick: '',
        checkPass:'xxxxxx',
        pass: '111111',
        role:''
      },
      options:'',
      rules2: {
        name: [
          { validator: name, trigger: 'blur' }
        ],
        pass: [
          { validator: pass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        userNick: [
          { validator: userNick, trigger: 'blur' }
        ],
        role:[
          { validator: role, trigger: 'change' }
        ]
      },
      activeNames: ['1']
    };
  },
  props:['dialogVisible','userData'],
  created() {
     Http.getAllRolelist().then(res =>{
       this.options = res.data.data
     })
    if(this.userData.id){
      this.unamesta = true,
      this.ruleForm2.name = this.userData.username;
      this.ruleForm2.userNick = this.userData.nick;
      this.ruleForm2.role = this.userData.role;
    }
  },
  methods:{
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const md5 = crypto.createHash("md5");
            md5.update(this.ruleForm2.pass);
          const psw = md5.digest('hex')
          const obj = {
            "username": this.ruleForm2.name,
            "password": psw,
            "nick": this.ruleForm2.userNick,
            "role": this.ruleForm2.role
          };

          this.addNewUser(obj)
          
        } else {
          return false;
        }
      });
    },
    addNewUser(obj){
      obj.status=1
      Http.addMonitor(obj)
      .then( res => {
        
        if( res.data.code == 200 ) { 
          this.$message.success('用户添加成功')
          this.$emit('showFun')
        } else if (res.data.code == -1003) {
          this.$message.error(`请求失败原因：${res.data.message}`)
          setTimeout(()=>{
            this.$router.push('/')
          },2000)
        } else {
          this.$message.error('用户添加失败')              
        }
      })
      .catch( error => {
        this.$message.error('服务器请求失败')
        
      })
    },
    editUser(){
      let psw='';
      const obj = {
        "username": this.ruleForm2.name,
        "id": this.userData.id,
        "nick": this.ruleForm2.userNick,
        "role": this.ruleForm2.role
      };
      if(this.ruleForm2.pass != '111111' || this.ruleForm2.checkPass != 'xxxxxx'){
        if(this.ruleForm2.checkPass == this.ruleForm2.pass){
          const md5 = crypto.createHash("md5");
            md5.update(this.ruleForm2.pass);
           psw = md5.digest('hex')
           obj.password = psw;
        } else {
          this.$message.error('两次密码不一致')
          return
        }
      };
      
      Http.eidtMonitor(obj)
      .then( res => {
        
        if( res.data.code == 200 ) { 
          this.unamesta = false;
          this.$message.success('用户修改成功')
          this.$emit('showFun')
        } else if (res.data.code == -1003) {
          this.$message.error(`请求失败原因：${res.data.message}`)
          setTimeout(()=>{
            this.$router.push('/')
          },2000)
        } else {
          this.$message.error('用户添加失败')              
        }
      })
      .catch( error => {
        this.$message.error('服务器请求失败')
        
      })
    },
    resetForm(formName) {
      this.unamesta = false;
      this.$refs[formName].resetFields();
      this.$emit('showFun')
    },
    handleRemove(file, fileList) {
      
    },
    handlePictureCardPreview(event, file, fileList) {
    },
    handleOK(responed) {
    },
    handleClose(done) {
      this.$refs["ruleForm2"].resetFields();
      this.$emit('showFun')
    },
  }
}
</script>
<style>
.chackmargin{
  margin-left:100px!important;
}

</style>